package service

import (
	"IM/define"
	"IM/helper"
	"IM/models"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"log"
	"net/http"
	"time"
)

var upgrader = websocket.Upgrader{}
var wc = make(map[string]*websocket.Conn)

func WebSocketMessage(c *gin.Context) {
	//获取WebSocket连接
	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": -1,
			"msg":  "系统异常: " + err.Error(),
		})
		return
	}
	defer conn.Close()
	uc := c.MustGet("user_claims").(*helper.UserClaims)
	//建立当前用户对应的连接信息关联
	wc[uc.Identity] = conn
	for {
		ms := new(define.MessageStruct)
		err := conn.ReadJSON(ms)
		if err != nil {
			log.Printf("read err: %v\n", err)
			return
		}
		// 判断用户是否属于当前消息体所在的房间
		_, err = models.GetUserRoomByUserIdentityRoomIdentity(uc.Identity, ms.RoomIdentity)
		if err != nil {
			log.Printf("UserIdentity: %v, RoomIdentity: %v Not Exists\n", uc.Identity, ms.RoomIdentity)
			return
		}
		// TODO 保存消息
		mb := &models.MessageBasic{
			UserIdentity: uc.Identity,
			RoomIdentity: ms.RoomIdentity,
			Data:         ms.Message,
			CreatedAt:    time.Now().Unix(),
			UpdatedAt:    time.Now().Unix(),
		}
		err = models.InsertOneMessageBasic(mb)
		if err != nil {
			log.Printf("[DB ERRROR]:%v\n", err)
			return
		}
		// 从关联表中查询当前房间的所有用户
		users, err := models.GetUsersByRoomIdentity(ms.RoomIdentity)
		if err != nil {
			log.Printf("[DB ERROR]:%v\n", err)
			return
		}
		for _, room := range users {
			// 仅给在特定房间的在线用户发送消息
			if cc, ok := wc[room.UserIdentity]; ok {
				err := cc.WriteMessage(websocket.TextMessage, []byte(ms.Message))
				if err != nil {
					log.Printf("write message err: %v\n", err)
					return
				}
			}
		}
	}
}
